<template>
  <div v-if="showPanel" id="lanhu-svg-panel" :class="{ collapsed: isCollapsed }">
    <div class="panel-header">
      <h3>
        🎨 拦截的SVG (<span>{{ svgCount }}</span
        >)
      </h3>
      <button class="toggle-btn" @click="togglePanel">{{ isCollapsed ? '+' : '−' }}</button>
    </div>
    <div class="panel-content" v-show="!isCollapsed">
      <div v-if="svgList.length === 0" id="empty-state">暂无拦截的SVG</div>
      <div v-else id="svg-list">
        <div v-for="(svg, index) in svgList" :key="index" class="svg-container">
          <div class="svg-item" @click="previewSvg(svg.url)">
            <div
              class="svg-preview"
              :style="{ backgroundImage: `url('${API_URL}/download?url=${svg.url}')` }"
            ></div>
            <div class="lanhu-setting-panel">
              <div
                class="setting-item"
                @click="copySvg(svg.url, svg.width, svg.height, 'vue')"
                data-type="vue"
              >
                V
              </div>
              <div
                class="setting-item"
                @click="copySvg(svg.url, svg.width, svg.height, 'react')"
                data-type="react"
              >
                R
              </div>
              <div
                class="setting-item"
                @click="copySvg(svg.url, svg.width, svg.height, 'flutter')"
                data-type="flutter"
              >
                F
              </div>
              <div
                class="setting-item"
                @click="copySvg(svg.url, svg.width, svg.height, 'link')"
                data-type="link"
              >
                LINK
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import browser from 'webextension-polyfill'
import md5 from 'crypto-js/md5'
import { API_URL, CDN_URL, COMPONENT_NAME } from '@/env'
import { toast } from '@/components/toast'

// 响应式状态
const showPanel = ref(true)
const isCollapsed = ref(false)
const svgList = ref<any[]>([])

// 计算属性
const svgCount = computed(() => svgList.value.length)

// 方法
const togglePanel = () => {
  isCollapsed.value = !isCollapsed.value
}

const previewSvg = (url: string) => {
  // 预览SVG功能
  console.log('预览SVG:', url)
}

const downloadSvg = async (url: string) => {
  try {
    const response = await fetch(`${API_URL}/download?url=${decodeURIComponent(url)}`)
    const data = await response.text()
    return data
  } catch (error) {
    console.error('下载SVG失败:', error)
    throw error
  }
}

const copySvg = async (url: string, width: string, height: string, type: string) => {
  try {
    console.log(`复制SVG为${type}格式:`, url)
    const svgContent = await downloadSvg(url)

    const cleanedSvg = cleanSvgContent(svgContent)
    const digest = hash(svgContent)
    await uploadSvg(cleanedSvg, digest)
    await writeText(type, digest, width, height)
  } catch (error) {
    console.error('复制SVG失败:', error)
  }
}

const writeText = async (type: string, digest: string, width: string, height: string) => {
  try {
    if (type === 'vue') {
      await fetch(`${API_URL}/copy`, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: `<${COMPONENT_NAME} icon="${digest}" :size="[${width},${height}]" />`,
      })
    }
    if (type === 'react') {
      await fetch(`${API_URL}/copy`, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: `<${COMPONENT_NAME} icon="${digest}" size={[${width},${height}]} />`,
      })
    }
    if (type === 'flutter') {
      await fetch(`${API_URL}/copy`, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: `${COMPONENT_NAME}(icon: "${digest}", size: (${width}, ${height}))`,
      })
    }
    if (type === 'link') {
      await fetch(`${API_URL}/copy`, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: `${CDN_URL}${digest}.svg`,
      })
    }
    toast.success('复制成功')
  } catch (error) {
    console.error('复制SVG摘要失败1:', error)
    toast.error('复制失败')
  }
}

const cleanSvgContent = (svgContent: string) => {
  try {
    // 清理转义的引号，解决 "AttValue: " or ' expected" XML parsing errors
    const cleaned = svgContent
      .replace(/\\"/g, '"') // 替换转义的双引号
      .replace(/\\'/g, "'") // 替换转义的单引号
      .replace(/&quot;/g, '"') // 替换HTML实体
      .replace(/&apos;/g, "'") // 替换HTML实体

    return cleaned
  } catch (error) {
    console.error('清理SVG内容失败:', error)
    return svgContent
  }
}

const hash = (s: string) => md5(s).toString()

const uploadSvg = async (svgContent: string, digest: string) => {
  try {
    // 检查文件是否存在
    try {
      await isFileExisted(digest)
      console.log('文件已存在')
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (_) {
      // 文件不存在，上传
      const uploadResponse = await fetch(`${API_URL}/upload`, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: svgContent,
      })
      const uploadResult = await uploadResponse.text()
      console.log('上传结果:', uploadResult)
    }
  } catch (error) {
    console.error('上传SVG失败:', error)
  }
}

const isFileExisted = async (digest: string) => {
  const response = await fetch(`${API_URL}/${digest}`)
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`)
  }
  return response
}

const updateSvgPanel = (newSvgList: any[]) => {
  svgList.value = newSvgList
  console.log('更新SVG面板:', newSvgList)
}

const setupMessageListener = () => {
  console.log('🔧 设置消息监听器...')

  browser.runtime.onMessage.addListener((request: any, sender, sendResponse) => {
    console.log('📨 Content script 收到消息:', request)

    if (request.action === 'svgCaptured') {
      console.log('✅ 收到 svgCaptured 消息，数据:', request.data)
      updateSvgPanel(request.data)
      sendResponse({ success: true })
    }
    if (request.action === 'getSvgSize') {
      try {
        const elements = document.querySelectorAll('.item_title')
        const ele = Array.prototype.filter.call(elements, (element) => {
          return element.textContent === '大小'
        })[0]
        let width = ele.nextElementSibling.textContent
        let height = ele.nextElementSibling.nextElementSibling.textContent
        width = width.replace('px', '').trim()
        height = height.replace('px', '').trim()
        sendResponse({ success: true, data: { width, height } })
      } catch (error) {
        // @ts-expect-error - error.message is a string
        sendResponse({ success: false, error: error.message })
      }
    }

    return true // 保持消息通道开放
  })

  // 通知 background script content script 已准备好
  setTimeout(() => {
    try {
      browser.runtime
        .sendMessage({
          action: 'contentScriptReady',
          url: window.location.href,
        })
        .catch((error) => {
          console.log('通知 background script 失败:', error.message)
        })
    } catch (error) {
      console.log('发送准备消息失败:', error.message)
    }
  }, 1000)

  console.log('✅ 消息监听器设置完成')
}

const observePageChanges = () => {
  try {
    const observer = new MutationObserver((mutations) => {
      try {
        mutations.forEach((mutation) => {
          if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
            onPageContentChanged()
          }
        })
      } catch (error) {
        console.log('处理页面变化时出错:', error.message)
      }
    })

    if (document.body) {
      observer.observe(document.body, {
        childList: true,
        subtree: true,
      })
    } else {
      document.addEventListener('DOMContentLoaded', () => {
        if (document.body) {
          observer.observe(document.body, {
            childList: true,
            subtree: true,
          })
        }
      })
    }
  } catch (error) {
    console.log('设置页面变化观察器失败:', error.message)
  }
}

const onPageContentChanged = () => {
  try {
    updatePageInfo()
  } catch (error) {
    console.log('处理页面内容变化时出错:', error.message)
  }
}

const getPageInfo = () => {
  const info = {
    title: document.title,
    url: window.location.href,
    projectName: extractProjectName(),
    pageName: extractPageName(),
    artboards: getArtboards(),
  }
  return info
}

const extractProjectName = () => {
  const selectors = [
    '[data-project-name]',
    '.project-name',
    '.breadcrumb .project',
    '.header-project-name',
    '.project-title',
  ]

  for (const selector of selectors) {
    const element = document.querySelector(selector)
    if (element) {
      return element.textContent?.trim() || ''
    }
  }

  const urlMatch = window.location.pathname.match(/\/project\/([^\/]+)/)
  if (urlMatch) {
    return decodeURIComponent(urlMatch[1]!)
  }

  return '未知项目'
}

const extractPageName = () => {
  const selectors = [
    '[data-page-name]',
    '.page-name',
    '.artboard-name',
    '.current-page',
    '.page-title',
  ]

  for (const selector of selectors) {
    const element = document.querySelector(selector)
    if (element) {
      return element.textContent?.trim() || ''
    }
  }

  return '未知页面'
}

const getArtboards = () => {
  const artboards: any[] = []
  const artboardElements = document.querySelectorAll('.artboard, [data-artboard], .canvas-item')

  artboardElements.forEach((element, index) => {
    const artboard = {
      id: element.id || `artboard-${index}`,
      name: getElementText(element, '.artboard-name, .title') || `画板 ${index + 1}`,
      dimensions: getElementDimensions(element),
      position: getElementPosition(element),
    }
    artboards.push(artboard)
  })

  return artboards
}

const getElementText = (element: Element, selector?: string) => {
  if (selector) {
    const textElement = element.querySelector(selector)
    return textElement ? textElement.textContent?.trim() || '' : ''
  }
  return element.textContent?.trim() || ''
}

const getElementDimensions = (element: Element) => {
  const rect = element.getBoundingClientRect()
  return {
    width: rect.width,
    height: rect.height,
  }
}

const getElementPosition = (element: Element) => {
  const rect = element.getBoundingClientRect()
  return {
    x: rect.left + window.scrollX,
    y: rect.top + window.scrollY,
  }
}

const updatePageInfo = () => {
  try {
    if (browser.runtime?.id) {
      browser.runtime
        .sendMessage({
          action: 'pageInfoUpdated',
          data: getPageInfo(),
        })
        .catch((error) => {
          if (
            error.message?.includes('Extension context invalidated') ||
            error.message?.includes('Could not establish connection')
          ) {
            console.log('扩展上下文已失效，忽略消息发送')
          } else {
            console.error('发送页面信息更新失败:', error)
          }
        })
    }
  } catch (error) {
    if (error.message?.includes('Extension context invalidated')) {
      console.log('扩展上下文已失效，停止发送消息')
    } else {
      console.error('更新页面信息时出错:', error)
    }
  }
}

// 生命周期
onMounted(() => {
  setupMessageListener()
  observePageChanges()
  console.log('蓝湖插件内容脚本已加载')
})

onUnmounted(() => {
  // 清理工作
})
</script>

<style scoped>
#lanhu-svg-panel {
  /* position: fixed;
  top: 20px;
  right: 20px; */
  width: 300px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

#lanhu-svg-panel.collapsed .panel-content {
  display: none;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  border-radius: 8px 8px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.toggle-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  color: #666;
}

.panel-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.svg-container {
  margin-bottom: 12px;
}

.svg-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.svg-item:hover {
  background: #e9ecef;
}

.svg-preview {
  width: 32px;
  height: 32px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 12px;
  flex-shrink: 0;
}

.svg-info {
  flex: 1;
  min-width: 0;
}

.svg-name {
  font-size: 12px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.svg-meta {
  font-size: 11px;
  color: #666;
  margin-top: 2px;
}

#empty-state {
  padding: 32px 16px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.lanhu-setting-panel {
  display: flex;
  gap: 8px;
  padding: 0 8px;
}

.setting-item {
  padding: 8px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 12px;
  color: #666;
}

.setting-item:hover {
  background: #e9ecef;
}
</style>
